import axios from 'axios'
import router from "@/router";
import { ElMessage } from 'element-plus';
import translate from 'i18n-jsautotranslate'

var instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 80000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8;',
        // "Authorization": "Bearer " + sessionStorage.getItem("token")
    }
})

//请求拦截器 
instance.interceptors.request.use((config: any) => {
    const token = window.localStorage.getItem('token');
    token && (config.headers.Authorization = token)
    if (config.method === 'POST') {
        config.data = JSON.stringify(config.data);
    }
    return config;
}, (error) =>
    Promise.reject(error));

//响应拦截器
instance.interceptors.response.use((response) => {
    if([-201,-205,-206,-207,-208,-209].includes(response.data.code)){
        ElMessage({
            message:`${response.data.msg}`,
            type:'warning'
        })
    }else if([-202].includes(response.data.code)){
        ElMessage({
            message:`${response.data.msg}`,
            type:'warning'
        })
        router.push({
            path: '/Sign'
        })
    }
  translate.execute();
    return response.data;
}, (error) => {
    if (error.response && error.response.status) {
        return Promise.reject(error);
    }
    return Promise.reject(error);
});

export default instance;